# -*- coding: utf-8 -*-
from flask import Flask, request, jsonify
from jianshu import jianshu

app = Flask(__name__)
blog = jianshu("5a7f510f1934")
HOST = "http://127.0.0.1:5000/"

@app.route("/article.list")
def article_list():
    with app.app_context():
        articles = blog.article(request.args.get("page", 1), request.args.get("type", "u"), request.args.get("id", None))
        r = []
        if articles:
            for a in articles:
                r.append({
                    "contentUrl": HOST+"article.detail?id=" + a["id"],
                    "title": a["title"],
                    "summary": a["summary"],
                    "time": a["time"],
                    "view": a["view"],
                    "imgSrc": a["imgSrc"]
                })
        return jsonify(r) 

@app.route("/article.detail")
def article_detail():
    with app.app_context():
        if request.args.get("id"):
            article = blog.detail(request.args.get("id"))
            if article:
                return jsonify({
                    "title": article["title"],
                    "time": article["time"],
                    "wordage": article["wordage"],
                    "tag": article["tag"],
                    "content": article["content"]
                })
        return jsonify({
            "title": "",
            "time": "",
            "wordage": None,
            "tag": "",
            "content": None
        })

@app.route("/notebook.list")
def notebook():
    with app.app_context():
        notebooks = blog.notebooks(request.args.get("page", 1))
        return jsonify({
            "notebooks": [ {"id":i["id"],"name":i["name"],"lsUrl":HOST+"article.list?page=1&type=nb&id="+str(i["id"])} for i in notebooks["notebooks"] ],
            "page": notebooks["page"],
            "total_pages": notebooks["total_pages"]
        })

@app.route("/user.info")
def user_info():
    with app.app_context():
        return jsonify(blog.info())

if __name__ == "__main__":
    app.run()
    